﻿using System;
using System.IO;
using System.Linq;
using System.Text;

namespace CloudManager.ThirdPartyProviders
{
    internal sealed class GoogleDriveProvider : CloudService
    {
        private const string guid = "ecc30fd0-4546-11e2-bcfd-0800200c9a66";

        //Based on batch file downloaded here: https://docs.google.com/file/d/0B8XlUYxdHr7XMDQwQVN0VmZKRlk/edit?pli=1

        internal GoogleDriveProvider()
        {
            Guid = guid;

            DisplayName = "Google Drive";
            Description = "Google Drive is a free service that lets you bring all your photos, docs, and videos anywhere.";
            InformationUrl = "https://drive.google.com/";
            AccountUrl = "https://drive.google.com";

            Url48x48 = "http://k37.kn3.net/7DDDA8544.png";
            Url40x40 = "http://k35.kn3.net/AA5EBCDA4.png";
            Url32x32 = "http://k31.kn3.net/022B096E1.png";
            Url24x24 = "http://k35.kn3.net/397FB33CC.png";
            Url20x20 = "http://k35.kn3.net/397FB33CC.png";
            Url16x16 = "http://k43.kn3.net/E5162FC3D.png";

            LocalFolder = GetGoolgeDrive().FullName;
        }


        internal static bool IsInstalled()
        {
            return File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Google\Drive\sync_config.db"));
        }

        internal static bool IsRegistered()
        {
            var re = new RegistryEditor();

            var keyObj = re.GetKey(BaseKey, false);

            var subKeys = keyObj.GetSubKeyNames();

            return subKeys.Contains(guid);
        }

        private DirectoryInfo GetGoolgeDrive()
        {
            var dbFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Google\Drive\sync_config.db");
            var t = Path.GetTempFileName();
            File.Copy(dbFilePath, t, true);
            var text = File.ReadAllText(t, Encoding.ASCII);

            var trim = text.Substring(text.IndexOf("local_sync_root_pathvalue") + 29);

            return new DirectoryInfo(trim.Substring(0, trim.IndexOf(char.ConvertFromUtf32(30))));
        }

    }
}
